package com.yneusoft.manage.service;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yneusoft.common.enums.ResultEnum;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.common.tool.JWTUtils;
import com.yneusoft.dao.entity.Staff;
import com.yneusoft.dao.mapper.StaffManageMapper;
import com.yneusoft.manage.model.result.GetImageCodeResult;
import com.yneusoft.manage.model.param.UserLoginParam;
import com.yneusoft.manage.model.result.UserLoginResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 登录管理 service
 */
@Service
public class LoginManageService {

    @Resource
    StaffManageMapper staffManageMapper;

    TimedCache<String,String> timedCache= CacheUtil.newTimedCache(60000);
    LineCaptcha lineCaptcha;

    /**
     * 获取图片验证码
     * @return 验证码密钥，验证码(base64)
     */
    public ResponseWrapper getImageCode(){
        RandomGenerator random=new RandomGenerator("0123456789abcdefghijklmnopqrsuvwxyzt",4);
        lineCaptcha = new LineCaptcha(110,40,4,30);
        lineCaptcha.setGenerator(random);
        String uuid= IdUtil.randomUUID();
        timedCache.put("imageCodeKey",uuid);
        GetImageCodeResult imageCodeResult=new GetImageCodeResult();
        imageCodeResult.setImageCodeKey(uuid);
        imageCodeResult.setImageCodeBase64(lineCaptcha.getImageBase64Data());
        return ResponseWrapper.markSuccess(imageCodeResult);
    }


    /**
     * 用户登录
     * @param param 登录请求参数
     * @return token，name
     */
    public ResponseWrapper userLogin(UserLoginParam param){
        String key=timedCache.get("imageCodeKey");
        if (key == null){
            return ResponseWrapper.markError(ResultEnum.CAPTCHA_TIMEOUT);
            //验证码密钥是否过期
        }else {
            if (!key.equals(param.getImageCodeKey())) {
                return ResponseWrapper.markError(ResultEnum.CAPTCHA_TIMEOUT);
                //验证码密钥是否错误
            }else {
                if (!lineCaptcha.verify(param.getImageCode())){
                    return ResponseWrapper.markError(ResultEnum.CAPTCHA_CHECK_ERROR);
                    //验证码校验是否失败
                }else {
                    LambdaQueryWrapper<Staff> wrap=new LambdaQueryWrapper<>();
                    wrap.eq(StringUtils.isNotBlank(param.getPhone()),Staff::getPhone,param.getPhone())
                            .eq(StringUtils.isNotBlank(param.getPassword()),Staff::getPassword,param.getPassword())
                            .ne(Staff::getStateId,0);
                    Staff s=staffManageMapper.selectOne(wrap);
                    if (s==null){
                        return ResponseWrapper.markError(ResultEnum.LOGIN_ERROR);
                    }else {
                        UserLoginResult loginResult=new UserLoginResult();
                        loginResult.setToken(JWTUtils.getToken(s.getAid()));
                        loginResult.setName(s.getName());
                        return ResponseWrapper.markSuccess(loginResult);
                        //用户校验是否成功
                    }
                }
            }
        }
    }

    /**
     * 根据token返回当前用户信息
     * @return name
     */
    public ResponseWrapper getCurrentUser(){
        HttpServletRequest request= ((ServletRequestAttributes)(Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))).getRequest();
        String token = request.getHeader("token");
        LambdaQueryWrapper<Staff> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Staff::getAid,JWTUtils.getClaim(token,"aid")).ne(Staff::getStateId,0);
        Staff staff=staffManageMapper.selectOne(wrapper);
        if (staff!=null){
            return ResponseWrapper.markSuccess(staff.getName());
        }else
            return ResponseWrapper.markError();
    }
}
